package com.hhm.interceptor;

import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                //获取name进行判断
                if ("login_token".equals(cookie.getName())){
                    //获取value--token
                    String token = cookie.getValue();

                    //获取jwt对象
                    JWT jwt = JWT.of(token);
                    //密钥
                    byte[] key = "1234567890".getBytes();
                    //校验token
                    boolean b = jwt.setKey(key).verify();
                    if (b){
                        //获取用户名、密码
                        Object username = jwt.getPayload("username");
                        Object uid = jwt.getPayload("uid");
                        //存入作用域
                        request.setAttribute("username", username);
                        request.setAttribute("uid", uid);
                        return true;
                    }
                }
            }
        }
        //没有token，重定向到登录
        response.sendRedirect("/user/toLogin");
        return false;
    }
}
